﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using CMS.BLL;

/// <summary>
///  清空MemacheCache和 Nginx缓存
/// </summary>
public class CacheClearBLL
{


    public static bool NewsClear(long id, bool isList = true, bool isNews = true)
    {
        try
        {
            CMSModel.CMSEntities dal = new CMSModel.CMSEntities();
            string[] types = null;
            if (isList)
            {
                types = dal.News_Type.Where(x => x.NewsId == id).Select(x => x.NewsTypeId).ToArray();
                foreach (var c in types)
                {
                    string[] keys = dal.MemcacheKey.Where(x => x.Key.Contains(c)).Select(x => x.Key).ToArray();
                    foreach (var d in keys)
                    {
                        MemcachedTools.Clear(d);
                        dal.MemcacheKey.DeleteObject(dal.MemcacheKey.First(x => x.Key == d));
                    }
                }
            }
            if (isNews)
            {

                string s = id.ToString();
                string[] keys = dal.MemcacheKey.Where(x => x.Key.Contains(s)).Select(x => x.Key).ToArray();
                foreach (var c in keys)
                {
                    MemcachedTools.Clear(c);
                    dal.MemcacheKey.DeleteObject(dal.MemcacheKey.First(x => x.Key == c));
                }
            }
            dal.SaveChanges();
            List<string> regLst = new List<string>();
            //新闻的正则表达式
            string reg1 = "news.emoney.cn/n_(.*)_([0-9]+)_" + id.ToString() + ".shtml(.*)";
            regLst.Add(reg1);
            reg1 = "news.emoney.cn/n_(.*)_([0-9]+)_" + id.ToString() + "_\\d{1,2}.shtml(.*)";
            regLst.Add(reg1);
            reg1 = "news.emoney.cn/NewsContent.aspx\\?ID=" + id.ToString() + "(.*)";
            regLst.Add(reg1);
            foreach (var c in types)
            {
                regLst.Add("news.emoney.cn/news_(.*)_" + c + "_([0-9]+).shtml(.*)");
                regLst.Add("news.emoney.cn/News.aspx\\?cid=" + c + "(.*)");
            }
            NginxPurge.AddReg(regLst);
        }
        catch
        {
        }
        return default(bool);
    }

    public static void ClearLike(string str)
    {
        CMSModel.CMSEntities dal = new CMSModel.CMSEntities();
        var keys= dal.MemcacheKey.Where(x => x.Key.Contains(str)).Select(x=>x.Key);
        MemcacheKeyBLL memcacheKeyBLL = new MemcacheKeyBLL();
        foreach (var d in keys)
        {
            MemcachedTools.Clear(d);
            memcacheKeyBLL.Delete(d);  
        }
    }

    static void Clear(object obj)
    {


    }
}